<?php
/**
 * Created by PhpStorm.
 * User: jswei
 * Date: 2019/3/9
 * Time: 16:55
 */

namespace app\admin\controller;

use app\admin\model\Proxy as MchModel;
use app\admin\model\ProxyWithdraw;
use app\admin\validate\Proxy as MchValidate;
use Naixiaoxin\ThinkWechat\Facade;
use think\db\Where;


class Proxy extends Base {
    protected static $payment  = null;
    public function __construct(){
        parent::__construct();
        $this->model = new MchModel;
        $this->validate = new MchValidate;
        self::$payment = Facade::payment();
    }

    /**
     * @param int $limit
     * @param int $page
     * @return \think\Response|\think\response\View
     * @throws \think\exception\DbException
     */
    public function index($limit=10,$page=1){
        $where = new Where();
        if (self::$mc_id) {
            $where['mc_id']=self::$mc_id;
        }
        $model_name = $this->model->getTable();
        $data = request()->post();
        if($data){
            if($data['name']){
                $where[$model_name.'.name']=['like','%'.trim($data['name']).'%'];
            }
            if($data['status']){
                $where[$model_name.'.status']=$data['status'];
            }
            if($data['date']){
                $t = explode('~',$data['date']);
                $start = strtotime($t[0]);
                $end = strtotime($t[1]);
                $where[$model_name.'.create_time']= ['between time',[$start,$end]];
            }
        }
        $list = $this->model->getList($where,$limit);
        if(request()->isAjax()){
            return $this->__s('',$list);
        }else{
            $this->assign('total',$list->total());
            $this->assign('list',$list);
            return view();
        }
    }

    /**
     * @param int $id
     * @return \think\response\View
     * @throws \think\exception\DbException
     */
    public function check($id=0){
        if(!$id){
            $this->error('缺少参数');
        }
        $info = $this->model->find($id);
        $this->assign('info',$info);
        return view();
    }

    /**
     * @param int $id
     * @param string $status
     * @param string $info
     * @return \think\Response
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function update($id=0,$status=3,$info=''){
        if(!$id){
            return $this->__e('缺少参数');
        }
        $info = $this->model->updateStatus($id,$status,$info,$out);
        if(!$info){
            return $this->__e($out);
        }
        return $this->__s('操作成功',['redirect'=>Url('proxy/index')]);
    }


    /**
     * @param int $id
     * @param int $status
     */
    public function status($id=0,$status=0){
        if(!$id || !$status){
            $this->__e('缺少参数');
        }
        $mch = $this->model->get($id);
        if(!$mch){
            $this->__e('商户不存在');
        }
        if($status==2){
            $mch->cross_time = time();
        }
        $mch->status = $status;
        if(!$mch->isUpdate(true)->save()){
            $this->__e('操作失败');
        }
        $this->__s('操作成功');
    }


    /**
     * 删除
     * @param int $id
     * @throws \Exception
     */
    public function del($id=0){
        if(!$id){
            $this->__e('缺少参数');
        }
        if(!$this->model->where('id','eq',$id)->delete()){
            $this->__e('删除失败');
        }
        $this->__s('删除成功');
    }

    /**
     * 生成二维码
     * @param int $id
     * @return \think\Response
     */
    public function create_qrcode($id=0){
        if(!$id){
            $this->error('缺少参数');
        }
        $info = $this->model->get($id);
        if(!$info){
            return $this->__e('申请不存在 ');
        }
        $url = request()->host();
        $url = "http://{$url}/client/apply.html?proxy_id={$id}";
        $data = qrcode($url);
        $info->qrcode = $data;
        if(!$info->save()){
            return $this->__e('生成失败 ');
        }
        return $this->__s('生成成功');
    }

    /**
     * 查看二维码
     * @param int $id
     * @return \think\Response
     * @throws \think\Exception\DbException
     */
    public function see_qrcode($id=0){
        if(!$id){
            return $this->__e('缺少参数');
        }
        $info = $this->model->field('id,qrcode')->get($id);
        if(!$info){
            return $this->__e('活动不存在');
        }
        if(!$info['qrcode']){
            return $this->__e('没有生成活动二维码');
        }
        return $this->__s('获取成功',$info);
    }


    /**
     * @param int $limit
     * @param int $page
     * @return \think\Response|\think\response\View
     * @throws \think\exception\DbException
     */
    public function withdraw($limit=10,$page=1){
        $where = new Where();
        $model = new ProxyWithdraw();
        $model_name = $model->getTable();
        $data = request()->post();
        if($data){
            if($data['proxy']){
                $proxy = new \app\admin\model\Proxy();
                $list = $proxy
                    ->whereLike('name',"%{$data['proxy']}%")
                    ->select();
                $ids = [];
                foreach ($list as $v){
                    array_push($ids,$v['id']);
                }
                $where[$model_name.'.proxy_id']=['in',$ids];
            }
            if($data['name']){
                $where[$model_name.'.name']=['like','%'.trim($data['name']).'%'];
            }
            if($data['status']){
                $where[$model_name.'.status']=$data['status'];
            }
            if($data['date']){
                $t = explode('~',$data['date']);
                $start = strtotime($t[0]);
                $end = strtotime($t[1]);
                $where[$model_name.'.create_time']= ['between time',[$start,$end]];
            }
        }
        $list = $model->getList($where,$limit);
        if(request()->isAjax()){
            return $this->__s('',$list);
        }else{
            $this->assign('total',$list->total());
            $this->assign('list',$list);
            return view();
        }
    }

    /**
     * @param int $id
     * @return \think\response\View
     */
    public function check_withdraw($id=0){
        if(!$id){
            $this->error('缺少参数');
        }
        $model = new ProxyWithdraw();
        $info = $model->find($id);
//        p($info);die;
        $this->assign('info',$info);
        return view();
    }

    /**
     * 确认提现
     * @param int $id
     * @param int $status
     * @param string $info
     * @return \think\Response
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function update_withdraw($id=0,$status=3,$info=''){
        if(!$id){
            return $this->__e('缺少参数');
        }
        $model = new ProxyWithdraw();
        $_info = $model->get($id);
        if(!$_info){
            return $this->__e('申请不存在');
        }
        if($_info['status']!=1){
            return $this->__e('申请已处理');
        }
        if($status==3){
            $_info->status = 3;
            $_info->fail_info = $info;
            $_info->update_time = time();
            if(!$_info->save()){
                return $this->__e('操作失败');
            }
            return $this->__s('操作成功',['redirect'=>Url('proxy/withdraw')]);
        }else{
            $open_id = $this->model->getOpenIdByProxyId($_info['proxy_id']);
            $this->redpack($_info['order_id'],$open_id,$_info['money'],'',$out);
            if($out['status']==2){
                $_proxy = $this->model->get($_info['proxy_id']);
                $_proxy->money = $_proxy['money'] - $_info['money'];
                $_proxy->save();
            }
            $_info->status = $out['status'];
            $_info->set_info = $out['set_info'];
            if(!$_info->save()){
                return $this->__e('操作失败');
            }
            return $this->__s('操作成功',['redirect'=>Url('proxy/withdraw')]);
        }
    }

    /**
     * 删除提现
     * @param int $id
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function del_withdraw($id=0){
        if(!$id){
            $this->__e('缺少参数');
        }
        $model = new ProxyWithdraw();
        if(!$model->where('id','eq',$id)->delete()){
            $this->__e('删除失败');
        }
        $this->__s('删除成功');
    }

    /**
     * @param string $order_id
     * @param string $open_id
     * @param int $money
     * @param string $remark
     * @param null $out
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function redpack($order_id='',$open_id='',$money=0,$remark='',&$out=null){
        $redpackData = [
            'mch_billno'   => $order_id,
            'scene_id'     => 'PRODUCT_5',
            'send_name'    => '天空文化传播',
            're_openid'    => $open_id,
            'total_num'    => 1,
            'total_amount' => $money * 100,
            'wishing'      => '代理推广费用',
            'act_name'     => '天空文化传播',
            'remark'       => $remark?$remark:'代理推广费用',
        ];
        $result = self::$payment->redpack->sendNormal($redpackData);
        if($result['return_code']!='SUCCESS'){
            $out = [
                'status'=>4,
                'set_info'=> '微信红包发送异常'
            ];
        }
        if($result['err_code']=='SENDNUM_LIMIT'
            || $result['err_code']=='NO_AUTH'){
            $out = [
                'status'=>4,
                'set_info'=> $result['return_msg']
            ];
        }
        if($result['err_code']=='SEND_FAILED'){
            $out = [
                'status'=>3,
                'set_info'=> $result['return_msg']
            ];
        }
        if($result['err_code']=='SYSTEMERROR'){
            self::$payment->redpack->sendNormal($redpackData);
        }
        if($result['result_code']=='SUCCESS'){
            $out = [
                'status'=>2,
                'set_info'=> $result['return_msg']
            ];
        }
    }
}